<template>
  <!-- 修改密码 -->
  <custom-modal
    width="500px"
    :visible="visible"
    :title="$t('modifyPassword')"
    :destroyOnClose="true"
    :maskClosable="false"
    :suring="loading"
    @ok="handleSubmit"
    @cancel="resetData"
  >
    <a-form-model
      ref="formComp"
      :model="formData"
      :rules="rules"
      layout="horizontal"
      class="AsteriskAfter newEditStyle"
      style="min-width:200px;"
    >
      <a-row>
        <a-col :md="24" :sm="24">
          <a-form-model-item :label="$t('serverPassword')" prop="sourcePassword">
            <a-input
              allow-clear
              :type="pwdInputConfigs.sourcePassword.type"
              v-model="formData.sourcePassword"
              :placeholder="$t('pleasePassword')">
              <a-icon
                :type="pwdInputConfigs.sourcePassword.iconType"
                slot="suffix"
                @click="tooglePwdType('sourcePassword')" />
            </a-input>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="24" :sm="24">
          <a-form-model-item :label="$t('newPassword')" prop="newPassword">
            <a-input
              allow-clear
              :type="pwdInputConfigs.newPassword.type"
              v-model="formData.newPassword"
              :placeholder="$t('pleaseInput') + $t('newPassword').toLowerCase()"
            >
              <a-icon :type="pwdInputConfigs.newPassword.iconType" slot="suffix" @click="tooglePwdType('newPassword')"/>
            </a-input>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="24" :sm="24">
          <a-form-model-item :label="$t('confirmNewPassword')" prop="confirmNewPassword">
            <a-input
              allow-clear
              :type="pwdInputConfigs.confirmNewPassword.type"
              :disabled="!formData.newPassword"
              :placeholder="$t('pleaseInput') + $t('newPassword').toLowerCase()"
              v-model="formData.confirmNewPassword">
              <a-icon
                :type="pwdInputConfigs.confirmNewPassword.iconType"
                slot="suffix"
                @click="tooglePwdType('confirmNewPassword')"/>
            </a-input>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
  </custom-modal>
</template>
<script>
import { mapActions } from 'vuex'
import CustomModal from '@/components/CustomModal/index.vue'
import userApi from '@/api/modules/system/user'
import md5 from 'md5'
import { checkTextLen } from '@/utils/validate'
const closedConfig = {
  type: 'password',
  iconType: 'eye-invisible'
}
const openedConfig = {
  type: 'input',
  iconType: 'eye'
}
const initFormData = {
  newPassword: '',
  sourcePassword: '',
  confirmNewPassword: ''
}
export default {
  name: 'ModifyPassword',
  components: {
    CustomModal
  },
  props: {
  },
  data () {
    const _this = this
    return {
      formItemLayout: {
        labelCol: { lg: { span: 24 }, sm: { span: 24 } },
        wrapperCol: { lg: { span: 24 }, sm: { span: 24 } }
      },
      visible: false,
      formData: { ...initFormData },
      rules: {
        sourcePassword: [{ required: true, message: this.$t('pleaseInput') }, { validator: checkTextLen(30) }],
        newPassword: [
          { required: true, message: this.$t('pleaseInput') },
          {
            validator: (rule, value, callback) => {
              _this.passwordValidator(rule, value, callback)
            }
          }
        ],
        confirmNewPassword: [
          { required: true, message: this.$t('pleaseInput') },
          {
            validator: (rule, value, callback) => {
              _this.password2Validator(rule, value, callback)
            }
          }
        ]
      },
      loading: false,
      pwdInputConfigs: {
        sourcePassword: { ...closedConfig },
        newPassword: { ...closedConfig },
        confirmNewPassword: { ...closedConfig }
      }
    }
  },
  methods: {
    ...mapActions(['Logout']),
    // ////修改密码
    // 验证密码
    passwordValidator (rule, value, callback) {
      const vm = this

      if (value === undefined) {
        callback(new Error(vm.$t('pleasePassword')))
        return
      }
      if (vm.formData.sourcePassword && value === vm.formData.sourcePassword) {
        callback(new Error(vm.$t('newPwdEqOldPwd')))
        return
      }
      if (!this.checkPwd(value, callback)) {
        return
      }
      if (vm.formData.confirmNewPassword) {
        vm.checkEqual(rule, value, callback)
        return
      }
      callback()
    },
    // 验证确认密码
    password2Validator (rule, value, callback) {
      if (value === undefined) {
        // eslint-disable-next-line callback-return
        callback(new Error(this.$t('passwordLimit')))
      }
      if (!this.checkPwd(value, callback)) {
        return
      }
      if (this.formData.newPassword) {
        this.checkEqual(rule, value, callback)
        return
      }
      callback()
    },
    checkPwd (value, callback) {
      const vm = this
      const pattern = /^.{6,30}$/
      if (!pattern.test(value)) {
        callback(new Error(vm.$t('passwordLimit')))
        return false
      }
      let level = 0
      if (/\d/.test(value)) {
        level += 1
      }
      if (/[a-z]/.test(value)) {
        level += 1
      }
      if (/[A-Z]/.test(value)) {
        level += 1
      }
      if (level < 3) {
        callback(new Error(vm.$t('passwordLimit')))
        return false
      }
      return true
    },
    checkEqual (rule, value, callback) {
      const { newPassword, confirmNewPassword } = this.formData
      if (newPassword.trim() !== confirmNewPassword.trim()) {
        callback(new Error(this.$t('twoPwdNotEq')))
        return
      }
      callback()
    },
    // 修改密码提交
    handleSubmit () {
      const vm = this
      vm.$refs.formComp.validate(valid => {
        if (valid) {
          this.loading = true
          const data = { ...this.formData }
          data.sourcePassword = md5(data.sourcePassword)
          data.newPassword = md5(data.newPassword)
          delete data.confirmNewPassword
          userApi.modifyLoginUserPwd(data).then(() => {
            this.$message.success(this.$t('successfullyOperation'))
            this.$nextTick(() => {
              setTimeout(() => {
                vm.Logout().then(() => {
                  window.location.reload()
                })
              }, 300)
            })
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    resetData () {
      this.visible = false
      this.formData = { ...initFormData }
      this.$nextTick(() => {
        if (!this.$refs.formComp) {
          return
        }
        this.$refs.formComp.resetFields()
        this.$refs.formComp.clearValidate()
      })
    },
    switchVisible (val) {
      this.visible = val
    },
    tooglePwdType (key) {
      const data = this.pwdInputConfigs[key]
      if (!data) {
        console.error('传递的参数' + key + '有误!')
        return
      }
      if (data.type === 'password') {
        this.pwdInputConfigs[key] = { ...openedConfig }
      } else {
        this.pwdInputConfigs[key] = { ...closedConfig }
      }
    }
  }
}
</script>
